package com.mifengs.mall.ui.web;


import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.CookieManager;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.model.LatLng;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.DefaultHandler;
import com.google.gson.Gson;
import com.mifengs.commonbase.util.DeviceInfoUtil;
import com.mifengs.commonbase.util.LogUtil;
import com.mifengs.commonbase.util.NetWorkUtils;
import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.commonbase.util.ToastUitl;
import com.mifengs.mall.Constant;
import com.mifengs.mall.MallApplication;
import com.mifengs.mall.R;
import com.mifengs.commonbase.base.BaseActivity;
import com.mifengs.commonbase.base.BaseFragment;
import com.mifengs.mall.di.component.DaggerWebFrgComponent;
import com.mifengs.mall.di.module.WebFrgModule;
import com.mifengs.mall.entity.ContactBean;
import com.mifengs.mall.entity.DeliveryPushBean;
import com.mifengs.mall.entity.JsCallAppFunction;
import com.mifengs.mall.entity.JsContactBean;
import com.mifengs.mall.entity.JsLocBean;
import com.mifengs.mall.entity.JsRespInfo;
import com.mifengs.mall.event.WebFrgEvent;
import com.mifengs.mall.ui.login.LoginActivity;
import com.mifengs.mall.ui.main.MainActivity;
import com.mifengs.mall.ui.main.ScanActivity;
import com.mifengs.mall.ui.my.version.CurrentVersionActivity;
import com.mifengs.mall.util.Contacts;
import com.mifengs.mall.util.GPSUtil;
import com.mifengs.mall.util.LocationUtil;
import com.mifengs.mall.util.ToIntentUtil;
import com.mifengs.mall.util.UIUtil;
import com.mifengs.mall.widget.MfProgressView;
import com.mifengs.mall.widget.MyWebView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

import static android.app.Activity.RESULT_OK;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link WebFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class WebFragment extends BaseFragment<WebFrgPresent> implements EasyPermissions.PermissionCallbacks,
        SwipeRefreshLayout.OnRefreshListener,WebFrgContract.View,MyWebView.OnProgressChangerListener ,MyWebView.onReceivedTitleListener,AMapLocationListener{

    @BindView(R.id.webview)
    MyWebView mWebView;
    @BindView(R.id.btn_retry)
    TextView mBtRetry;
    @BindView(R.id.rl_error)
    RelativeLayout mRlError;
    @BindView(R.id.spin)
    MfProgressView mWaitingView;
    @BindView(R.id.v_status_bar)
    View mVStatusBar;
    @BindView(R.id.swipe_container)
    SwipeRefreshLayout mSwipeContainer;
    @BindView(R.id.myProgressBar)
    ProgressBar mProgressBar;
    @BindView(R.id.rl_404)
    RelativeLayout mRl404;

    private final String TAG = "WebFragment";
    private static final int TYPE_REQUEST_PERMISSION = 1;
    private static final int TYPE_GALLERY = 2;
    public static final int REQUEST_PERMISSION_STORAGE = 3;
    public static final int REQUEST_WEIXIN = 4;
    public static final int REQUEST_ALIPAYS = 5;
    public static final int REQUEST_PERMISSION_LOCATION = 5;
    public static final int REFRESH_H5_MY = 6;
    public static final int SWIPE_REFRESH = 7;
    public static final int CONTACTS_PERMISSION_LOCATION = 8;
    private static final int REQUST_SCAN_ACTIVITY = 9;
    private static final int REQUEST_PERMISSION_CAMERA = 10;
    private static final String TITLE = "title";
    private static final String PATH = "path";
    private String mTitle;
    private String mPath;
    private boolean isError = false;
    private int mStatusColor = Color.WHITE;
    private boolean isFromMainActivity = false;
    private boolean isRealTabPage= false;     //标记 是否 真正的 h5 页面
    //private boolean isNotNeedTopBar = true;
    private boolean isBackToFinish =false;//true 直接返回到上一个界面
    private boolean is404Page = false;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private LatLng mLoclatLng;
    private String contactsMobile;
    private String contactsJson;
    private AMapLocation mAmaplocation;
    private CallBackFunction mLocBackFunction;
    private CallBackFunction mBookBackFunction;
    private CallBackFunction mScanBackFunction;
    private String contactName;


    public WebFragment() {
        // Required empty  public constructor
    }

    @Override
    public void initInjector() {
        DaggerWebFrgComponent.builder()
                .webFrgModule(new WebFrgModule(this))
                .build()
                .inject(this);
    }

    public static WebFragment newInstance(String path, String title) {
        WebFragment fragment = new WebFragment();
        Bundle args = new Bundle();
        args.putString(TITLE, title);
        args.putString(PATH, path);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        if (getArguments() != null) {
            mTitle = getArguments().getString(TITLE);
            mPath = getArguments().getString(PATH);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_web, container, false);
        ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {
        if (getActivity() instanceof MainActivity) {
            isFromMainActivity = true;
            int statusHeight = UIUtil.getStatusHight();
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mVStatusBar.getLayoutParams();
            layoutParams.height = statusHeight;
            mVStatusBar.setVisibility(View.VISIBLE);
            mVStatusBar.setBackgroundColor(mStatusColor);
        }
        mSwipeContainer.setOnRefreshListener(this);
        mSwipeContainer.setEnabled(false);
        //Glide.with(this).load(R.drawable.ic_mifeng_progress).into(mWaitingView);
        mWebView.setWebViewClient(new FundWebViewClient(mWebView));
        mWebView.addJavascriptInterface(new AndroidtoJs(), "android");
        Map extraHeaders = new HashMap();
        extraHeaders.put("Referer", "https://www.mifengs.com");
        mWebView.loadUrl(mPath, extraHeaders);
        mBtRetry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWebView.reload();
            }
        });
        mWebView.setProgressListener(this);
        mWebView.setOnReceivedTitleListener(this);
        initJsNeedMethod();
    }


    public void setPath(String url){
        this.mPath = url;
        if (getArguments() != null) {
            Bundle bundle = getArguments();
            bundle.putString(PATH, url);
            setArguments(bundle);
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if(requestCode == REQUEST_PERMISSION_LOCATION){
            if(mLocBackFunction!=null){
                JsRespInfo<JsLocBean> jsRespInfo = new JsRespInfo<>();
                jsRespInfo.setStatus(201);
                jsRespInfo.setMsg("定位权限未打开");
                jsRespInfo.setResult(new JsLocBean());
                String json = new Gson().toJson(jsRespInfo);
                mLocBackFunction.onCallBack(json);
            }
            ((BaseActivity)getActivity()).showPermissionDeniedDialog(getActivity(),getString(R.string.setting_loaction_permission));
        }
    }


    public void toCamera() {
        mWebView.toCamera();
    }

    public void onActivityNoBack() {
        mWebView.onActivityNoBack();
    }

    @Override
    public void onRefresh() {
        mWebView.reload();
        mHandler.sendEmptyMessageDelayed(SWIPE_REFRESH,1000);
    }

    @Override
    public MyWebView getWebView() {
        return mWebView;
    }

    @Override
    public void setIsRealTabPage(boolean isRealTabPage) {
        this.isRealTabPage = isRealTabPage;
    }

    @Override
    public void setSwipeEnableTrue() {
       // if(isFromMainActivity && isRealTabPage){
        if(isFromMainActivity){
            if(mPath!=Constant.H5_CLASSIFT&&!(mPath.startsWith(Constant.H5_Nearby)))
                if(mSwipeContainer !=null){
                    mSwipeContainer.setEnabled(true);
                }
        }
    }

    @Override
    public void onProgressChanged(int progress) {
        if(mProgressBar!=null&&mWebView!=null){
            if (progress == 100) {
                mProgressBar.setVisibility(View.INVISIBLE);
                //mWebView.setVisibility(View.VISIBLE);
                if(isFromMainActivity){
                    mWebView.setTouchEnable(true);
                }
            }else{
                if (View.INVISIBLE == mProgressBar.getVisibility()) {
                    mProgressBar.setVisibility(View.VISIBLE);
                }
//                if(!isFromMainActivity&&(View.VISIBLE == mWebView.getVisibility())){
//                    mWebView.setVisibility(View.GONE);
//                }
                if(isFromMainActivity){
                    mWebView.setTouchEnable(false);
                }
                mProgressBar.setProgress(progress);
            }
        }
    }

    @Override
    public void recevied(String title) {
        if(getActivity() instanceof CommonWebActivity){
            if(title.equals(getString(R.string.web_cant_open))){
                is404Page = true;
                mRl404.setVisibility(View.VISIBLE);
                ((CommonWebActivity) getActivity()).setTitle("");
            }else{
                ((CommonWebActivity) getActivity()).setTitle(title);
            }
        }
    }

    private boolean needClearHistory= false;


    public void setNeedClearHistory(boolean needClearHistory) {
        this.needClearHistory = needClearHistory;
    }

    private class FundWebViewClient extends BridgeWebViewClient {

        public FundWebViewClient(BridgeWebView webView) {
            super(webView);
        }

        @Override
        public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
//            super.doUpdateVisitedHistory(view, url, isReload);
            if (needClearHistory) {
                mWebView.clearHistory();
                needClearHistory = false;
//                Toast.makeText(getContext(),"doUpdateVisitedHistory",Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            LogUtil.i("WebFragment:url=",url);
            try {
                url = URLDecoder.decode(url, "UTF-8");
            } catch (UnsupportedEncodingException var4) {
                var4.printStackTrace();
            }

            if(url.startsWith("yy://return/")) {
                mWebView.handlerReturnData(url);
                return true;
            } else if(url.startsWith("yy://")) {
                mWebView.flushMessageQueue();
                return true;
            } else {
                return handleUrl(url);
            }
        }


        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            if(NetWorkUtils.isNetworkAvailable(MallApplication.getInstance())){
                if(mWaitingView!=null){
                    mWaitingView.setVisibility(View.VISIBLE);
                }
                isError = false;
                isRealTabPage = false;
                isBackToFinish = false;
            }else{
                ToastUitl.show("网络连接失败，请检查您的网络设置",Toast.LENGTH_SHORT);
            }

        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (mWaitingView != null) {
                mWaitingView.setVisibility(View.INVISIBLE);
            }
            if(mRl404!=null&&is404Page==false){
                mRl404.setVisibility(View.GONE);
            }
            if (!isError) {
                if (mRlError != null) {
                    mRlError.setVisibility(View.INVISIBLE);
                    mPresenter.loadJs();
                }
            } else {
                if (mRlError != null) {
                    mRlError.setVisibility(View.VISIBLE);
                }
            }
            CookieManager cookieManager = CookieManager.getInstance();
            String cookieStr = cookieManager.getCookie(url);
            if(!TextUtils.isEmpty(cookieStr)){
                LogUtil.i("cookie",cookieStr);
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            isError = true;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }

    }


    @AfterPermissionGranted(REQUEST_PERMISSION_LOCATION)
    public void needLoc() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_COARSE_LOCATION
                , Manifest.permission.ACCESS_FINE_LOCATION};
        if (EasyPermissions.hasPermissions(getContext(), perms)) {
           // mLocationClient.start();
            dingwei();
        } else {
            EasyPermissions.requestPermissions(this, "您需要定位权限",
                    REQUEST_PERMISSION_LOCATION, perms);
        }
    }

    @AfterPermissionGranted(CONTACTS_PERMISSION_LOCATION)
    public void contactsPermission() {
        String[] perms = {Manifest.permission.READ_CONTACTS};
        if (EasyPermissions.hasPermissions(getContext(), perms)) {
            Uri uri = ContactsContract.Contacts.CONTENT_URI;
            Intent intent=new Intent(Intent.ACTION_PICK,uri);
            startActivityForResult(intent,CONTACTS_PERMISSION_LOCATION);
            if("100".equals(PreferenceUtils.getContacts(getContext()))){
                List<ContactBean> contactBeanList = Contacts.getPhoneContacts(getContext());
                contactsJson =  contactsJson(contactBeanList);
                mPresenter.saveContactsInfo();
            }
        } else {
            EasyPermissions.requestPermissions(this, "您需要打开通讯录权限",
                    CONTACTS_PERMISSION_LOCATION, perms);
        }
    }

    private String contactsJson(List<ContactBean> contactsList){
        JSONObject object = new JSONObject();
        JSONArray json = new JSONArray();
        for(ContactBean contactBean:contactsList){
            JSONObject jo = new JSONObject();
            try {
                jo.put("contactsName",contactBean.getContactsName());
                jo.put("contactsPhone",contactBean.getContactsPhone());
                json.put(jo);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
//        try {
//            object.put("contactsInfo","{"+json+"}".toString());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        return json.toString();

    }

    public void dingwei(){
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(getContext());
            mlocationClient.setLocationListener(this);
            mLocationOption = LocationUtil.getDefaultOption();
            mlocationClient.setLocationOption(mLocationOption);
            mlocationClient.startLocation();
        }else{
            mlocationClient.startLocation();
        }
    }

    @Override
    public void onLocationChanged(AMapLocation amaplocation) {
        if (amaplocation != null) {
            if (amaplocation != null && amaplocation.getErrorCode() == 0) {
                mLoclatLng = new LatLng(amaplocation.getLatitude(), amaplocation.getLongitude());
                    //   mAMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE));
                    // mlocationClient.stopLocation();
                mAmaplocation = amaplocation;
                mlocationClient.stopLocation();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(mWebView!=null)
                            mWebView.evaluateJavascript("javascript:callBack()", new ValueCallback<String>() {
                                @Override
                                public void onReceiveValue(String value) {
                                    //此处为 js 返回的结果
                                    //  Toast.makeText(WebActivity.this,value,Toast.LENGTH_LONG).show();

                                }
                            });
                            JsCallAppFunction<JsLocBean> jsCallAppFunction = new JsCallAppFunction<JsLocBean>();
                            jsCallAppFunction.setFunctionName("getLocation");
                            JsLocBean bean = new JsLocBean();
                            double[] doubles = GPSUtil.gcj02_To_Bd09(mLoclatLng.latitude,mLoclatLng.longitude);
                            bean.setLat(doubles[0]+"");
                            bean.setLng(doubles[1]+"");
                            bean.setCityName(mAmaplocation.getCity());
                            jsCallAppFunction.setArgs(bean);
                            Gson gson = new Gson();
                            String returnJson = gson.toJson(jsCallAppFunction);
                            if(mLocBackFunction!=null){
                                JsRespInfo<JsLocBean> jsRespInfo = new JsRespInfo<>();
                                jsRespInfo.setResult(bean);
                                jsRespInfo.setStatus(200);
                                String json = gson.toJson(jsRespInfo);
                                mLocBackFunction.onCallBack(json);
                            }
                            mWebView.loadUrl("javascript:appCallBack('"+returnJson+"')");
                        }
                });
            } else {
                if(mLocBackFunction!=null){
                    JsRespInfo<JsLocBean> jsRespInfo = new JsRespInfo<>();
                    jsRespInfo.setStatus(201);
                    jsRespInfo.setResult(new JsLocBean());
                    jsRespInfo.setMsg(amaplocation.getErrorInfo());
                    String json = new Gson().toJson(jsRespInfo);
                    mLocBackFunction.onCallBack(json);
                }
            }
        }
    }


    // 继承自Object类
    public class AndroidtoJs extends Object {

        @JavascriptInterface
        public void getLocation() {
            LogUtil.i("WebFragment", "定位");
            needLoc();
        }

        @JavascriptInterface
        public String getResult() {
            //return mBDLocation.getLatitude() + "," + mBDLocation.getLongitude();
            LogUtil.i("WebFragment：经纬度：",mLoclatLng.latitude+","+mLoclatLng.longitude);
            double[] doubles = GPSUtil.gcj02_To_Bd09(mLoclatLng.latitude,mLoclatLng.longitude);

            return doubles[0]+","+doubles[1];
        }

        @JavascriptInterface
        public void refreshToLogin() {
            mHandler.sendEmptyMessage(REFRESH_H5_MY);
        }

        @JavascriptInterface
        public void saveProductID(String currProdId){
            PreferenceUtils.saveProDuctId(getContext(),currProdId);
        }

        @JavascriptInterface
        public String appToken(){
            return PreferenceUtils.getToken();
        }

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == MyWebView.TYPE_CAMERA) { // 相机选择
                mWebView.onActivityCallBack(true, null);
            } else if (requestCode == MyWebView.TYPE_GALLERY) {// 相册选择
                if (data != null) {
                    Uri uri = data.getData();
                    if (uri != null) {
                        mWebView.onActivityCallBack(false, uri);
                    } else {
                        Toast.makeText(getContext(), "获取数据为空", Toast.LENGTH_LONG).show();
                    }
                }
            }else if(requestCode == MyWebView.TYPE_LOGIN){
                if(getContext() instanceof CommonWebActivity){
                    String url = mWebView.getUrl();
                    if(!TextUtils.isEmpty(url)){
                        mWebView.loadUrl(mWebView.getUrl());
                    }else{
                        finish();
                    }
                }
            }else if(requestCode == CONTACTS_PERMISSION_LOCATION){
                //获取选择的联系人信息
                Uri uri=data.getData();
                String contact[]= Contacts.getContacts(uri,getContext());
                if(contact!=null){
                    contactName = contact[0];
                    contactsMobile = contact[1];
                    contactsMobile = contactsMobile.trim();
                    contactsMobile = contactsMobile.replace(" ","");
                    JsContactBean bean = new JsContactBean();
                    bean.setName(contactName);
                    bean.setPhone(contactsMobile);
                    String json = getBeanStringJsRespInfo(bean);
                    if(mBookBackFunction!=null){
                        mBookBackFunction.onCallBack(json);
                    }
                }
            }else if(requestCode == REQUST_SCAN_ACTIVITY){
                if(mScanBackFunction !=null){
                    String content = data.getStringExtra("content");
                    mScanBackFunction.onCallBack(getBeanStringJsRespInfo(content));
                }
            }
        }else {
            if (requestCode == REQUEST_WEIXIN) {
                mWebView.loadUrl("javascript:qryPayState()");
                mWebView.loadUrl("javascript:callJS()");
            } else if (requestCode == mWebView.TYPE_CAMERA) {
                mWebView.onActivityNoBack();
            } else if (requestCode == mWebView.TYPE_GALLERY) {
                mWebView.onActivityNoBack();
            }
        }
    }

    private <T> String getBeanStringJsRespInfo(T t){
        JsRespInfo<T> jsRespInfo = new JsRespInfo<>();
        jsRespInfo.setStatus(200);
        jsRespInfo.setResult(t);
        return new Gson().toJson(jsRespInfo);
    }


    public boolean canGoBack() {
        if(mWebView!=null){
            return mWebView.canGoBack();
        }else{
            return false;
        }
    }

    public void goBack() {
        if(isBackToFinish){
            if(mWebView!=null){
                finish();
            }
        }else{
            is404Page = false;
            mWebView.goBack();
        }

        //mPresenter.loadJsToSetTitle();
    }


    public void setStatusBarColor(int color) {
        this.mStatusColor = color;
    }

    /**
     * 处理页面需要加载的url 决定是跳转还是内部加载
     *
     * @param url
     * @return
     */
    private boolean handleUrl(String url) {
         if(url.contains(Constant.LOGIN_URL)){
            Intent intent = new Intent(getContext(), LoginActivity.class);
            startActivityForResult(intent,MyWebView.TYPE_LOGIN);
            if(getContext() instanceof CommonWebActivity){
                //finish();
                return true;
            }else{
                return true;
            }
        }
        if(url.startsWith(Constant.ORDER_URL)&&(getContext() instanceof MainActivity)){
            ToIntentUtil.toCommonIntent(url,getContext());
            reloadShopCartPage();
            return true;
        }

        if (url.startsWith("mailto:") || url.startsWith("geo:") || url.startsWith("tel:")) {
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
            } catch (Exception e) {

            }
        }else if (url.startsWith("weixin://wap/pay?")) {
            try {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                startActivityForResult(intent, REQUEST_WEIXIN);
                return true;
            } catch (ActivityNotFoundException e) {
                Toast.makeText(getContext(), "请安装最新版微信", Toast.LENGTH_LONG).show();
                return false;
            }
        } else if (url.startsWith("app://")) {
            mPresenter.handleOperation(url);
        } else {
            if (isFromMainActivity) {
                if(mWebView.getUrl().startsWith(Constant.H5_Nearby)){
                    ToIntentUtil.toCommonIntent(url,getContext());
                    return true;
                }
                if (isRealTabPage) {
                    ToIntentUtil.toCommonIntent(url,getContext());
                    return true;
                } else {
                    return insideLoad(url);
                }
            } else {
                return insideLoad(url);
            }
        }
        return true;
    }


    private boolean insideLoad(String url) {
        Map extraHeaders = new HashMap();
        extraHeaders.put("Referer", "https://www.mifengs.com");
        if(mWaitingView!=null&&Build.VERSION.SDK_INT<26){
            mWebView.loadUrl(url, extraHeaders);
        }
        return false;
    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case REFRESH_H5_MY:
                    mWebView.loadUrl(Constant.H5_MY);
                    break;
                case SWIPE_REFRESH:
                    mSwipeContainer.setRefreshing(false);
                    break;
            }
        }
    };

    public void reloadAccountPage(){
        if(mWebView!=null){
            mWebView.loadUrl(Constant.H5_MY);
        }
    }

    public void reloadShopCartPage(){
        if(mWebView!=null){
            mWebView.loadUrl(Constant.H5_CART);
        }
    }

    @Override
    public void isBackToFinish(boolean isBackToFinish) {
        this.isBackToFinish = isBackToFinish;
    }

    @Override
    public void goBackWithdrawal(String predepositUrl, String withdrawalUrl) {
        needClearHistory = true;
        mWebView.setWebViewClient(new FundWebViewClient(mWebView));
        mWebView.loadUrl(withdrawalUrl);
    }

    @Override
    public void getContactsInfo() {
        contactsPermission();
    }

    @Override
    public String contactsInfo() {
        return contactsJson;
    }

    @Override
    public void getJsCallAppFunction(JsCallAppFunction jsCallAppFunction) {
//        mWebView.loadUrl("javascript:appCallback()");
        JsCallAppFunction js = new JsCallAppFunction();
        js.setFunctionName("123");
        js.setIsReturn(1);
        String s = "";
        mWebView.loadUrl("javascript:appCallback("+s+")");
    }

    @Override
    public void getLocation(int isReturn) {
        needLoc();
    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(WebFrgEvent event) {
        switch (event.action) {
            case WebFrgEvent.SYNCCOOKIES:
                mWebView.syncCookie();
                break;
            case WebFrgEvent.WEIXIN_PAY:
                mPresenter.payClose();
                break;
            case WebFrgEvent.DELIVERY_PUSH:
                DeliveryPushBean bean = event.getDeliveryPushBean();
                pushStoreMessageHandle(bean);
                break;
        }
    }


    @Override
    public void onDestroy() {
        if( mWebView!=null) {

            // 如果先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码，需要先onDetachedFromWindow()，再
            // destory()
            ViewParent parent = mWebView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(mWebView);
            }
            mWebView.stopLoading();
            // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
            mWebView.getSettings().setJavaScriptEnabled(false);
            mWebView.clearHistory();
            mWebView.clearView();
            mWebView.removeAllViews();
            mWebView.destroy();

        }
        EventBus.getDefault().unregister(this);

        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;

        super.onDestroy();

    }

    private void initJsNeedMethod() {
        mWebView.setDefaultHandler(new DefaultHandler());
        mWebView.registerHandler("submitFromWeb", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                LogUtil.i(TAG,"handler = submitFromWeb, data from web = " + data);
                function.onCallBack("submitFromWeb exe, response data 中文 from Java");
            }

        });
        mWebView.registerHandler("loadPageFinsh", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if(mWebView!=null){

                }
            }
        });
        mWebView.registerHandler("getLocation", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                needLoc();
                mLocBackFunction = function;
            }
        });
        mWebView.registerHandler("getAddressBook", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                contactsPermission();
                mBookBackFunction = function;
            }
        });
        mWebView.registerHandler("scanQRCode", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                needCamera();
                mScanBackFunction = function;
            }
        });
        mWebView.registerHandler("backToFinish", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Intent intent = new Intent(getContext(),MainActivity.class);
                startActivity(intent);
            }
        });
        mWebView.registerHandler("openVersionPage", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Intent intent = new Intent(getContext(),CurrentVersionActivity.class);
                startActivity(intent);
            }
        });

        mWebView.registerHandler("currentVersion", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                function.onCallBack(getBeanStringJsRespInfo("v_"+ DeviceInfoUtil.getAppVersion(getContext())));
            }
        });

    }


    private void pushStoreMessageHandle(DeliveryPushBean bean){
        JsRespInfo<DeliveryPushBean> jsRespInfo = new JsRespInfo<>();
        jsRespInfo.setStatus(200);
        jsRespInfo.setResult(bean);
        String json = new Gson().toJson(jsRespInfo);
        mWebView.callHandler("storeMessageHandle", json, new CallBackFunction() {
            @Override
            public void onCallBack(String data) {

            }
        });
    }

    @AfterPermissionGranted(REQUEST_PERMISSION_CAMERA)
    public void needCamera() {
        String[] perms = {Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(getActivity(), perms)) {
            startScan();
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.need_camera_permission),
                    REQUEST_PERMISSION_CAMERA, perms);
        }
    }



    private void startScan() {
        Intent intent = new Intent(getContext(), ScanActivity.class);
        intent.putExtra("scanType",ScanActivity.TYPE_SCAN_QUHUO);
        startActivityForResult(intent,REQUST_SCAN_ACTIVITY);
    }





}
